package com.bing.picture;

import static com.bing.util.AssertUtils.notBlank;
import static com.bing.util.AssertUtils.notNull;

import java.io.IOException;
import java.io.InputStream;

public abstract class AbastractPicture implements Picture {

	protected String pk;

	protected String name;

	protected InputStream inputStream;

	protected PictureFormat pictureFormat;

	protected long size;

	protected String pictureUrl;

	protected AbastractPicture() {
	}

	AbastractPicture(InputStream inputStream, String pk) {

		notNull(inputStream, "picture inputstream must not be null!");
		notBlank(pk, "pk must not be blank!");
		this.inputStream = inputStream;
		this.pk = pk;
	}

	@Override
	public String pk() {
		return this.pk;
	}

	@Override
	public InputStream pictureInputStream() {
		return this.inputStream;
	}

	@Override
	public PictureFormat pictureFormat() {

		if (null != pictureFormat) {
			return pictureFormat;
		}
		String[] data = this.name().split("\\.");
		return this.pictureFormat = PictureFormat.getPictureFormat(data[data.length - 1]);
	}

	@Override
	public long size() {

		try {
			if (0 == this.size) {
				this.size = this.inputStream.available();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return this.size;
	}

	@Override
	public String pictureUrl() {
		return this.pictureUrl;
	}

	@Override
	public int hashCode() {

		int hash = 17;
		return 31 * hash + pk().hashCode();
	}

	@Override
	public boolean equals(Object obj) {

		if ((null == obj) || !(obj instanceof Picture)) {
			return false;
		}
		if (this.pk().equals(((Picture) obj).pk())) {
			return true;
		}
		return false;
	}
}
